﻿using DongFangGuoKai.WMSPlatform.Commn.ApiResultModule;
using DongFangGuoKai.WMSPlatform.Core.Conts;
using DongFangGuoKai.WMSPlatform.Domain.Enums;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Service.LogApp;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Security.Claims;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers
{
    /// <summary>
    /// 自定义BaseController，扩展控制器
    /// </summary>
    public class ApiBaseController : ControllerBase
    {
        public ApiBaseController()
        {

        }


        public ILogService LogService { get; }

        public ApiBaseController(ILogService logService)
        {
            LogService = logService;
        }


        #region Respons 
        protected async Task<IActionResult> SuccessAsync<TRespons>(TRespons respons, string msg = "OK") where TRespons : class
        {
            ApiDataResult<TRespons> res = new ApiDataResult<TRespons>()
            {
                Code = 200,
                Data = respons,
                Msg = msg,
                Success = true

            };
            return await Task.FromResult(new JsonResult(res));
        }
        protected async Task<IActionResult> SuccessAsync(string msg = "OK")
        {
            ApiBaseResult res = new ApiBaseResult()
            {
                Code = 200,
                Msg = msg,
                Success = true
            };
            return await Task.FromResult(new JsonResult(res));
        }

        protected IActionResult Success<TRespons>(TRespons respons, string msg = "OK") where TRespons : class
        {
            ApiDataResult<TRespons> res = new ApiDataResult<TRespons>()
            {
                Code = 200,
                Data = respons,
                Msg = msg,
                Success = true

            };
            return new JsonResult(res);
        }
        protected IActionResult Success<TRespons>(TRespons respons, int count, string msg = "OK") where TRespons : class
        {
            ApiDataResult<TRespons> res = new ApiDataResult<TRespons>()
            {
                Code = 200,
                Data = respons,
                Msg = msg,
                Success = true,
                Count = count

            };
            return new JsonResult(res);
        }
        protected IActionResult Success(string msg = "OK")
        {
            ApiBaseResult res = new ApiBaseResult()
            {
                Code = 200,
                Msg = msg,
                Success = true
            };
            return new JsonResult(res);
        }

        protected IActionResult Failed(string msg = "Failed", int code = 500)
        {
            ApiBaseResult res = new ApiBaseResult()
            {
                Code = code,
                Msg = msg,
                Success = false

            };
            return new JsonResult(res);
        }
        protected async Task<IActionResult> FailedAsync(string msg = "Failed", int code = 500)
        {
            ApiBaseResult res = new ApiBaseResult()
            {
                Code = code,
                Msg = msg,
                Success = false

            };
            return await Task.FromResult(new JsonResult(res));
        }

        protected async Task<IActionResult> ResultAsync(string msg, int code)
        {
            var res = new ApiBaseResult()
            {
                Code = code,
                Msg = msg
            };
            return await Task.FromResult(new JsonResult(res));
        }
        protected async Task<IActionResult> ResultAsync<TRespons>(TRespons tRespons)
        {
            return await Task.FromResult(new JsonResult(tRespons));
        }

        protected async Task<TRespons> ResponsAsync<TRespons>(TRespons tRespons)
        {
            return await Task.FromResult(tRespons);
        }

        protected TRespons Respons<TRespons>(TRespons respons)
        {
            return respons;
        }
        #endregion

        //接口日志服务

        protected bool CreateInterfaceLog(string name, string url, int callWay, string inParam, out t_InterfaceLog log)
        {
            log = null;

            try
            {
                string path = HttpContext.Request.Path; // 相对请求路径
                string userName = HttpContext.User.FindFirstValue(HttpContextItemKeyName.USER_NAME);
                string userId = HttpContext.User.FindFirstValue(HttpContextItemKeyName.USER_ID);
                EmInterfaceLogType logType = EmInterfaceLogType.Other;
                if (url.Contains("PDAHandler"))
                {
                    logType = EmInterfaceLogType.PDA;
                }
                else if (url.Contains("External"))
                {
                    logType = EmInterfaceLogType.ERP;
                }
                log = new t_InterfaceLog
                {
                    Name = name,
                    Url = path,
                    CallWay = callWay,
                    InParam = inParam,
                    Status = 0,
                    CreateDate = DateTime.Now,
                    LogType = logType,
                    Direction = 1,
                };
                if (userName != null)
                {

                    log.CreateUserName = userName;
                }
                if (userId != null)
                {
                    int id = 0;
                    int.TryParse(userId, out id);
                    log.CreateUserId = id;
                }
                bool result = LogService.AddInterfaceLog(log);
                if (!result)
                {
                    log = null;
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {

                return false;

            }


        }

        protected bool InterfaceCallFinished(t_InterfaceLog log, bool isOK = true, string errorMsg = "")
        {
            try
            {
                if (log == null || log.Id <= 0)
                {
                    return false;
                }
                DateTime createDate = log.CreateDate.GetValueOrDefault();
                DateTime now = DateTime.Now;
                int totalMilliseconds = (int)now.Subtract(createDate).TotalMilliseconds;

                log.CallMillisecond = totalMilliseconds;
                log.Status = isOK ? 1 : 2;
                log.ErrorMsg = errorMsg;

                bool result = LogService.UpdateInterfaceLog(log);
                return result;
            }
            catch
            {
                return false;
            }
        }
    }
}
